"""
权限系统
"""
from enum import Enum
from functools import wraps
from typing import List
from fastapi import HTTPException, status


class UserRole(str, Enum):
    """用户角色"""
    SUPER_ADMIN = "super_admin"      # 超级管理员
    CITY_MANAGER = "city_manager"    # 城市管理员
    VENUE_MANAGER = "venue_manager"  # 场地管理员
    USER = "user"                    # 普通用户


class Permission(str, Enum):
    """权限定义"""
    # 场地权限
    VENUE_VIEW_ALL = "venue:view:all"           # 查看所有场地
    VENUE_VIEW_CITY = "venue:view:city"         # 查看本城市场地
    VENUE_CREATE = "venue:create"               # 创建场地
    VENUE_EDIT_ALL = "venue:edit:all"           # 编辑所有场地
    VENUE_EDIT_CITY = "venue:edit:city"         # 编辑本城市场地
    VENUE_DELETE = "venue:delete"               # 删除场地
    VENUE_AUDIT = "venue:audit"                 # 审核场地
    
    # 用户权限
    USER_VIEW = "user:view"                     # 查看用户
    USER_MANAGE = "user:manage"                 # 管理用户
    
    # 城市管理员权限
    CITY_MANAGER_VIEW = "city_manager:view"     # 查看城市管理员
    CITY_MANAGER_MANAGE = "city_manager:manage" # 管理城市管理员
    
    # 数据统计权限
    STATS_VIEW_ALL = "stats:view:all"           # 查看所有统计
    STATS_VIEW_CITY = "stats:view:city"         # 查看本城市统计
    
    # 反馈权限
    FEEDBACK_VIEW_ALL = "feedback:view:all"     # 查看所有反馈
    FEEDBACK_VIEW_CITY = "feedback:view:city"   # 查看本城市反馈
    FEEDBACK_HANDLE = "feedback:handle"         # 处理反馈


# 角色权限映射
ROLE_PERMISSIONS = {
    UserRole.SUPER_ADMIN: [
        # 超管拥有所有权限
        perm for perm in Permission
    ],
    UserRole.CITY_MANAGER: [
        Permission.VENUE_VIEW_CITY,
        Permission.VENUE_CREATE,
        Permission.VENUE_EDIT_CITY,
        Permission.STATS_VIEW_CITY,
        Permission.FEEDBACK_VIEW_CITY,
        Permission.FEEDBACK_HANDLE,
    ],
    UserRole.VENUE_MANAGER: [
        Permission.VENUE_VIEW_CITY,
        Permission.VENUE_EDIT_CITY,
    ],
    UserRole.USER: []
}


def check_permission(user, permission: Permission) -> bool:
    """检查用户是否有指定权限"""
    user_role = getattr(user, 'role', UserRole.USER)
    if isinstance(user_role, str):
        try:
            user_role = UserRole(user_role)
        except ValueError:
            user_role = UserRole.USER
    
    user_permissions = ROLE_PERMISSIONS.get(user_role, [])
    return permission in user_permissions


def require_permission(*permissions: Permission):
    """
    权限装饰器
    用法: @require_permission(Permission.VENUE_CREATE)
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            # 从 kwargs 中获取 current_user
            current_user = kwargs.get('current_user')
            if not current_user:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="未登录"
                )
            
            # 检查是否有任意一个权限
            has_permission = False
            for perm in permissions:
                if check_permission(current_user, perm):
                    has_permission = True
                    break
            
            if not has_permission:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="权限不足"
                )
            
            return await func(*args, **kwargs)
        return wrapper
    return decorator


def require_role(*roles: UserRole):
    """
    角色装饰器
    用法: @require_role(UserRole.SUPER_ADMIN, UserRole.CITY_MANAGER)
    """
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            current_user = kwargs.get('current_user')
            if not current_user:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="未登录"
                )
            
            user_role = getattr(current_user, 'role', UserRole.USER)
            if isinstance(user_role, str):
                try:
                    user_role = UserRole(user_role)
                except ValueError:
                    user_role = UserRole.USER
            
            # 超级管理员拥有所有角色权限
            if user_role == UserRole.SUPER_ADMIN:
                return await func(*args, **kwargs)
            
            # 检查是否有指定角色
            if user_role not in roles:
                raise HTTPException(
                    status_code=status.HTTP_403_FORBIDDEN,
                    detail="权限不足"
                )
            
            return await func(*args, **kwargs)
        return wrapper
    return decorator

